package com.lvmama.pangolin.timer.processor;




import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.lvmama.pangolin.HBaseOper.HotelHBEntityOperation;
import com.lvmama.pangolin.busi.config.ConfigManager;
import com.lvmama.pangolin.busi.timer.TimerManager;
import com.lvmama.pangolin.busi.timer.TimerManagerAssist;
import com.lvmama.pangolin.common.Constant;
import com.lvmama.pangolin.common.DateUtil;
import com.lvmama.pangolin.common.JSONUtil;
import com.lvmama.pangolin.common.RowkeyGenerator;
import com.lvmama.pangolin.common.StringTools;
import com.lvmama.pangolin.entity.LogVO;
import com.lvmama.pangolin.entity.Timer;
import com.lvmama.pangolin.entity.hotel.HotelCommodityDetail;
import com.lvmama.pangolin.entity.hotel.HotelProductDetail;
import com.lvmama.pangolin.entity.lmm.LMMCareProduct;
import com.lvmama.pangolin.hbaseutil.HBaseUtils;
import com.lvmama.pangolin.hotel.service.HotelProductService;
import com.lvmama.pangolin.lmm.service.LMMCareProductService;
import com.lvmama.pangolin.service.OperLogService;
import com.lvmama.pangolin.service.TimerService;
import com.lvmama.pangolin.timer.CommonJob;
import com.lvmama.pangolin.util.HttpSignUtil;
import com.lvmama.pangolin.util.HttpsUtil;
import com.lvmama.pangolin.util.SpringContextUtil;

/**
 * 
* @ClassName: SynLMMHotelProduct 
* @Description: TODO
* @author yuanchi
* @date 2017年8月17日 上午11:35:47
 */
public class SynLMMHotelProduct extends CommonJob {

	
	@Autowired
	private LMMCareProductService careProductService;
	
	@Autowired
	private OperLogService operLogService;
	
	@Autowired
	private TimerService timerService;
	
	@Autowired
	private HBaseUtils hBaseUtils;
	
	private Logger logger = Logger.getLogger(SynLMMHotelProduct.class);
	
	private String url = "http://m.lvmama.com/other/router/rest.do?";
	
	private  Date TimerDate = null; 
	
	@Autowired
	private HotelProductService hotelProductService;
	
	@Autowired
	private HotelHBEntityOperation hotelHBEntityOperation;
	
	
	
	@Override
	public void runJob(JobExecutionContext context, String parameter)
	{
		logger.info("-----------同步LMM产品数据开始-----------");
		
		String configParam = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.JOB_DATAKEY);
		String task_id = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.TASK_ID);
		String timerId = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.TIMER_ID);
		String timerCode = (String) context.getJobDetail().getJobDataMap()
				.get(TimerManager.TIMER_CODE);
		String syscode=System.getProperties().getProperty("SYSCODE");
		syscode = StringTools.isValid(syscode)?syscode:"PUBLIC";
		
		
		ConfigManager config = ConfigManager.getInstance();
		url = config.getParamValue(configParam, "HOTEL_URL"
				,"http://m.lvmama.com/other/router/rest.do?");
		
		if(careProductService == null)
		{
			careProductService = (LMMCareProductService) SpringContextUtil
					.getBean(LMMCareProductService.class);
		}
		if(timerService == null)
		{
			timerService = (TimerService) SpringContextUtil
					.getBean(TimerService.class);
		}
		//保存产品信息
		if (hotelProductService == null)
		{
			hotelProductService = (HotelProductService) SpringContextUtil
					.getBean(HotelProductService.class);
		}
		//获取timer最新信息
		Timer timer = new Timer();
		timer.setTimer_id(timerId);
		timer.setSyscode(syscode);
		List<Timer> timerList = timerService.queryTimerList(timer);
		String message = null;
		LMMCareProduct record = new LMMCareProduct();
		List<LMMCareProduct> prodList = null;
		boolean sucessFlag = false;
		
		Date comeDate  = null;
		Date leaveDate = null;
		
		String companyCode = Constant.LMM_C_CODE;
		
		if(timerList != null && timerList.size() > 0)
		{
			Timer timerVO = timerList.get(0);
			int runNum = timerVO.getRun_num();
			int retryNum = timerVO.getRetry_num();
			String status = timerVO.getTimer_status();
			TimerDate = timerVO.getCreate_time();
			if(TimerDate == null)
			{
				TimerDate = new Date();
			}
			record.setDealFlag(0);
			record.setBusinessCode("HOTEL");
			if("0".equals(status))
			{
				if(runNum == 0)
				{
					//任务第一次执行，产品表处理标识统一改成0，任务执行次数默认+1
					timerService.updateRunNumByCon(timerId);
					careProductService.updateDealFlag(record);
				}
				else if (runNum < retryNum)
				{
					//任务执行次数+1
					timerService.updateRunNumByCon(timerId);
				}
				//获取处理标识为0的所有产品信息
				prodList = careProductService.selectByCond(record);
				if(runNum>=retryNum)
				{
					
					//记录异常日志
					if(prodList != null && !prodList.isEmpty())
					{
						message = "任务已经重试最大次数，依然存在产品信息同步异常导致产品信息未同步成功！任务默认成功。";
						logger.error("任务已经重试最大次数，依然存在产品信息同步异常导致产品信息未同步成功！");
						prodList.clear();
						//默认成功
						sucessFlag = true;
					}
					
				}
				
			}
		}
		//存在需要同步查询的产品信息
		int errorCount = 0;
		int successCount = 0;
		Calendar  cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, 1);
		comeDate =  cal.getTime();
		cal.add(Calendar.DAY_OF_MONTH, 1);
		leaveDate = cal.getTime();
		
		String come = DateUtil.yyyyMMdd.format(comeDate);
		String leave = DateUtil.yyyyMMdd.format(leaveDate);
		if(prodList != null && !prodList.isEmpty())
		{
			HotelProductDetail product = null;
			List<HotelCommodityDetail> commodityList = null;
			
			for (LMMCareProduct careProduct : prodList)
			{
				try
				{
					String prodId = careProduct.getProductId();
					String cityCode = careProduct.getCityCode();
					//获取产品信息
					product = transferProdData(prodId,task_id,timerCode,come,leave);
					if(product == null)
					{
						continue ;
					}
					product.setTaskId(task_id);
					product.setCityCode(cityCode);
					product.setTaskDate(TimerDate);
					product.setComeDate(comeDate);
					product.setLeaveDate(comeDate);
					product.setCompanyCode(companyCode);
					product.setUpdateTime(new Date());
					product.setPlatformCode("WAP");
					//获取商品列表信息
					String lowestPrice = null;
					commodityList = transferCommodityData(prodId,task_id,come,leave);
					if(commodityList != null && !commodityList.isEmpty())
					{
						int commoditySum = commodityList.size();
						int preferentialNum = 0;
						int commodityTypeNum = 0;
						Set<String> typeSet = new HashSet<String>();
						for (HotelCommodityDetail commodity : commodityList)
						{
							
							if(!StringTools.isValid(lowestPrice))
							{
								lowestPrice = commodity.getSalePrice();
							}
							else if(StringTools.isValid(commodity.getSalePrice()))
							{
								lowestPrice = compare(lowestPrice,commodity.getSalePrice());
							}
								
							//优惠数量
							if(StringTools.isValid(commodity.getPreferential()))
							{
								preferentialNum ++;
							}
							typeSet.add(commodity.getCommodityType());
//							typeSet.add(commodity.getRoomType());
							commodity.setTaskId(task_id);
							commodity.setTaskDate(TimerDate);
							commodity.setCompanyCode(companyCode);
							commodity.setUpdateTime(new Date());
							commodity.setCityCode(cityCode);
							
						}
						
						commodityTypeNum = typeSet.size();
						product.setCommodityTypeNum(commodityTypeNum);
						product.setPreferentialNum(preferentialNum);
						product.setCommodityNum(commoditySum);
						product.setLowestPrice(lowestPrice);
						
					}
					
					hotelProductService.saveHotelProdAndCom(product,commodityList,TimerDate);
					saveDataToHbase(product,commodityList);
					record.setDealFlag(1);
					record.setProductId(prodId);
					careProductService.updateDealFlag(record);
					successCount ++;
					sleep(1000);
				}catch (Exception e)
				{
					logger.error(careProduct.toString(),e);
					errorCount ++;
				}
				
			}
			
		}
		if(!sucessFlag)
		{
			//获取处理标识为0的所有产品信息.二次检查
			record.setDealFlag(0);
			record.setProductId(null);
			prodList = careProductService.selectByCond(record);
			if(prodList == null || prodList.isEmpty())
			{
				sucessFlag = true;
			}
		}
		
		if(sucessFlag)
		{
			try
			{
				message = message != null ? message:"SUCESS";
				Map<String,Object> param = new HashMap<String,Object>();
				param.put("timer_status", "5");
				param.put("error_desc", message);
				param.put("timer_id", timerId);
//				param.put("oper_time", timerId);
				timerService.updateTimerByCon(param);
				new TimerManagerAssist().removeJob(timerCode);
			}
			catch (Exception e)
			{
			}
		}
		message = message != null ? message: "同步产品数据完成,successCount : " 
				+ successCount + " errorCount ：" + errorCount ;
		logger.info(message);
		logger.info("-----------同步LMM产品数据结束-----------");
		
		
		
	}
	
	private String compare(String num1,String num2)
	{
		String last = null;
		try
		{
			
			if(StringTools.isValid(num1) && StringTools.isValid(num2))
			{
				if(Double.compare(Double.parseDouble(num1), Double.parseDouble(num2)) >=0)
				{
					last = num1;
				}
				else
				{
					last = num2;
				}
			}
			else if(StringTools.isValid(num1))
			{
				last = num1;
			}
			else if(StringTools.isValid(num1))
			{
				last = num2;
			}
		}catch (Exception e)
		{
			logger.error("比较异常！",e);
		}
		
		return last;
	}
	private void saveDataToHbase(HotelProductDetail prod,List<HotelCommodityDetail> commodityList)
	{
		Date date = new Date();
		Date comeDate = prod.getComeDate();
		//保存产品信息
		if (hotelHBEntityOperation == null)
		{
			hotelHBEntityOperation = (HotelHBEntityOperation) SpringContextUtil
					.getBean(HotelHBEntityOperation.class);
		}
		if(prod != null)
		{
			String productRowkey = RowkeyGenerator.generateProductRowkeyWithCompany(prod.getProductId(),
					prod.getCompanyCode(), comeDate,prod.getTaskId() );
			prod.setId(productRowkey);
			prod.setCreateTime(date);
			prod.setUpdateTime(date);
			hotelHBEntityOperation.saveHotelProduct(prod ,Constant.HOTEL_PRODUCT_H, Constant.HB_VARIABLE_FAMILY);
		}
		if(commodityList != null && !commodityList.isEmpty())
		{
			for (HotelCommodityDetail commodity : commodityList)
			{
				String rowkey = RowkeyGenerator.generateCommodityRowkeyWithCompany(commodity.getCommodityId(), commodity.getCompanyCode(), comeDate,commodity.getProductId());
				commodity.setId(rowkey);
				commodity.setCreateTime(date);
				commodity.setUpdateTime(date);
				hotelHBEntityOperation.saveHotelCommodity(commodity, Constant.HOTEL_COMMODITY_H, Constant.HB_VARIABLE_FAMILY);
				hotelHBEntityOperation.saveHistoryPrice(prod,commodity,rowkey,Constant.HB_VARIABLE_FAMILY,Constant.HOTEL_COMMODITY_PRICE_H);
			}
		}
		
	}
	
	
	private void sleep(long milliseconds)
	{
		try
		{
			Thread.sleep(milliseconds);
		}
		catch (InterruptedException e)
		{
		}
	}
	
	
	private  HotelProductDetail transferProdData(String prodId,String task_id,String timerCode,String arrivalDate,String departureDate) throws Exception
	{
		HotelProductDetail product = null;
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("method", "api.com.csa.resorthotel.getProductDetail");
		param.put("version", "1.0.0");
		param.put("udid", "wap");
		param.put("productId", prodId);
		param.put("arrivalDate", arrivalDate);
		param.put("departureDate", departureDate);
		String requestURL = HttpSignUtil.genReqUrl(url, param);
		String json = HttpsUtil.requestGet(requestURL);
		JSONObject jo = JSONUtil.getObject(json);
		if(jo!= null && "true".equals(jo.getString("success")))
		{
			JSONObject jsonData = jo.getJSONObject("data");
			product = new HotelProductDetail();
			product.setProductId(prodId);
			if(jsonData.containsKey("productAddress"))
			{
				product.setHotelAddr(jsonData.getString("productAddress"));
			}
			product.setHotelName(jsonData.getString("productName"));
			if(jsonData.containsKey("sellPrice"))
			{
				product.setLowestPrice(jsonData.getString("sellPrice"));
			}
			if(jsonData.containsKey("hotelStar"))
			{
				product.setStarLevel(jsonData.getString("hotelStar"));
			}
			else
			{
				product.setStarLevel("暂无星级评定");
			}
			if(jsonData.containsKey("description"))
			{
				System.out.println(jsonData.getString("description"));
//				product.setIntroduction(jsonData.getString("description"));
			}
			if(jsonData.containsKey("commentGoodRate"))
			{
				product.setScore(jsonData.getString("commentGoodRate"));
			}
			if(jsonData.containsKey("largeImages"))
			{
				JSONArray imageArr = jsonData.getJSONArray("largeImages");
				if(imageArr != null && imageArr.size() > 0)
				{
					product.setImageNum(imageArr.size()+"");
				}
				else
				{
					product.setImageNum("0");
				}
				
			}
			
			product.setCreateTime(TimerDate);
			product.setIsLink(0);
			product.setTaskId(task_id);
			
			
			
		}
		else
		{
			String errorMessage = jo.getString("message");
			insertLog(task_id,timerCode,prodId,requestURL,errorMessage);
			throw new Exception(errorMessage);
		}
		
		return product;
		
	}
	
	private void insertLog(String taskId,String timerCode,String product_id,String url,String  message)
	{
		try
		{
			LogVO log = new LogVO();
			log.setBatch_num(taskId);
			log.setTask_id(taskId);
			//任务生成异常
			log.setLog_type("F");
			log.setError_desc(message);
			log.setTimer_code(timerCode);
			log.setTask_date(TimerDate);
			log.setUrl(url);
			log.setProduct_id(product_id);
			log.setCompany_code("LMM_C_CODE");
			log.setBusi_type("门票");
			if(operLogService == null )
			{
				operLogService = (OperLogService) SpringContextUtil.getBean(OperLogService.class);
			}
			operLogService.insertOperLog(log);
		}
		catch (Exception e)
		{
			logger.error("插入日志表失败！",e);
		}
		logger.info("上次同类型任务未完成，请检查处理！");
	}
	
	private List<HotelCommodityDetail>  transferCommodityData(String prodId,String taskId,String arrivalDate,String departureDate)
	{
		List<HotelCommodityDetail> comodityList =  new ArrayList<HotelCommodityDetail>();
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("method", "api.com.csa.resorthotel.getGoodsList");
		param.put("version", "1.0.0");
		param.put("productId", prodId);
		param.put("arrivalDate", arrivalDate);
		param.put("departureDate", departureDate);
		param.put("udid", "wap");
		String requestURL = HttpSignUtil.genReqUrl(url, param);
		String json =  HttpsUtil.requestGet(requestURL);
		JSONObject jo = JSONUtil.getObject(json);
		if(jo!= null && "true".equals(jo.getString("success")))
		{
			JSONObject jsonData = jo.getJSONObject("data");
			if(jsonData != null)
			{
				JSONArray jsonArr = jsonData.getJSONArray("list");
				if(jsonArr != null && jsonArr.size() > 0)
				{
					JSONObject item = null;
					JSONArray itemDatas = null;
					for(int i=0;i<jsonArr.size();i++)
					{
						item = jsonArr.getJSONObject(i);
						if(item == null)
							continue;
						itemDatas = item.getJSONArray("ropGoodsResponseList");
						HotelCommodityDetail commodity = null;
						if(itemDatas != null && itemDatas.size() > 0)
						{
							for (Object object : itemDatas)
							{
								String goodsId = ((JSONObject)object).getString("goodsId");
								commodity = transferCommodity(prodId,goodsId,taskId,arrivalDate,departureDate);
								comodityList.add(commodity);
							}
							
								
						}
					}
				}
				
			}
		}
		
		
		return comodityList;
		
	}
	
	private HotelCommodityDetail  transferCommodity(String prodId,String goodsId,String taskId,String arrivalDate,String departureDate)
	{
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("method", "api.com.csa.resorthotel.getGoodsDetail");
		param.put("version", "1.0.0");
		
		param.put("productId", prodId);
		param.put("goodsId", goodsId);
		param.put("arrivalDate", arrivalDate);
		param.put("departureDate", departureDate);
		param.put("udid", "wap");
		
		String requestURL = HttpSignUtil.genReqUrl(url, param);
		String json =  HttpsUtil.requestGet(requestURL);
		JSONObject jo = JSONUtil.getObject(json);
		
		HotelCommodityDetail commodity = null;
		if(jo!= null && "true".equals(jo.getString("success")))
		{
			JSONObject commodityData = jo.getJSONObject("data");
			if(commodityData != null)
			{
				if(commodityData.containsKey("sellPrice") &&
						StringTools.isValid(commodityData.getString("sellPrice")))
				{
					commodity= new HotelCommodityDetail();
					commodity.setProductId(prodId);
					commodity.setProductId(prodId);
					commodity.setTaskId(taskId);
					if(commodityData.containsKey("branchName"))
					{
						commodity.setCommodityType(commodityData.getString("branchName"));
//						commodity.setRoomType(commodityData.getString("branchName"));
					}
					if(commodityData.containsKey("floor"))
					{
						commodity.setFloor(commodityData.getString("floor"));
					}
					if(commodityData.containsKey("roomArea"))
					{
						commodity.setArea(commodityData.getString("roomArea"));
					}
					if(commodityData.containsKey("sellPrice"))
					{
						commodity.setSalePrice(commodityData.getString("sellPrice"));
					}
					if(commodityData.containsKey("goodsId"))
					{
						commodity.setCommodityId(commodityData.getString("goodsId"));
					}
					if(commodityData.containsKey("goodsName"))
					{
						commodity.setCommodityName(commodityData.getString("goodsName"));
					}
					if(commodityData.containsKey("breakFastDesc"))
					{
						commodity.setBreakfast(commodityData.getString("breakFastDesc"));
					}
					if(commodityData.containsKey("window"))
					{
						commodity.setWindow(commodityData.getString("window"));
					}
					if(commodityData.containsKey("addBedFlag"))
					{
						commodity.setIncreaseBed(commodityData.getString("addBedFlag"));
					}
					if(commodityData.containsKey("maxVisitor"))
					{
						commodity.setPeopleNum(commodityData.getString("maxVisitor"));
					}
					if(commodityData.containsKey("bedType"))
					{
						commodity.setBedType(commodityData.getString("bedType"));
					}
					if(commodityData.containsKey("cancelStrategy"))
					{
						commodity.setCancelRule(commodityData.getString("cancelStrategy"));
					}
					if(commodityData.containsKey("clientPromotionTitle"))
					{
						commodity.setPreferential(commodityData.getString("clientPromotionTitle"));
					}
					if(commodityData.containsKey("broadband"))
					{
						commodity.setBroadband(commodityData.getString("broadband"));
					}
					
					
					commodity.setCreateTime(TimerDate);
					
				}
				
				
			}
		}
		
		return commodity;
		
	}
	
	
	/** 
	* @Title: main 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param args    设定文件 
	* @return void    返回类型 
	* @throws 
	*/
	public static void main(String[] args)
	{
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("method", "api.com.csa.resorthotel.getGoodsList");
//		param.put("method", "api.com.csa.resorthotel.getGoodsDetail");
		param.put("version", "1.0.0");
		
		param.put("productId", "1404101");
		param.put("arrivalDate", "2017-8-19");
		param.put("departureDate", "2017-8-20");
		param.put("udid", "wap");
//		param.put("goodsId",   "3918130");
		String url = "http://m.lvmama.com/other/router/rest.do?";
		String requestURL = HttpSignUtil.genReqUrl(url, param);
		System.out.println(requestURL);
		
//		System.out.println(ArrayList.class.isArray());
	}
	
}
